package test002;

import java.io.IOException;
import java.security.GeneralSecurityException;

import javax.servlet.http.*;

import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.User;
import com.google.gdata.client.http.AuthSubUtil;
import com.google.gdata.util.AuthenticationException;

@SuppressWarnings("serial")
public class Test002Servlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		resp.setContentType("text/html");

		System.err.println("getQueryString" + req.getQueryString());

		String paramToken = req.getParameter("token");
		System.err.println("paramToken" + paramToken);

		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		if (user != null) {
			if (paramToken != null) {
				String token = AuthSubUtil.getTokenFromReply(req
						.getQueryString());
				String sessionToken = "";
				try {
					sessionToken = AuthSubUtil.exchangeForSessionToken(token,
							null);
					MyContacts mycons = new MyContacts(user, sessionToken);
					resp.getWriter()
							.println(mycons.getMyGroups());
				} catch (AuthenticationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (GeneralSecurityException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {

				String next = req.getRequestURL().toString();
				String scope = "http://www.google.com/m8/feeds/";
				boolean secure = false;
				boolean session = true;
				resp.sendRedirect(AuthSubUtil.getRequestUrl(next, scope,
						secure, session));
			}
		} else {
			resp.sendRedirect(userService.createLoginURL(req.getRequestURL()
					.toString()));
		}

	}

}
